//
//  HELPersonVC.m
//  sanda
//
//  Created by 陈武琦 on 16/7/11.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "HELPersonVC.h"
#import "HELPersonTableHeadView.h"
#import "HELPersonCollectionViewCell.h"
#import "HELPersonSettingVC.h"
#import "HELCompulsoryVC.h"
#import "HELExamVC.h"
#import "HELModifyPwdVC.h"
#import "HELMeetingInfo.h"
#import "HELStatisticVC.h"
#import "HELUserInfoM.h"
#import "UIButton+WebCache.h"
#import "HELSigninVC.h"
#import "CWQButtonWithBadge.h"
#import "HELDownloadVC.h"

//#import "UIViewController+SQExtension.h"
#define headViewHeight cwqGetCustomHeight(180.0)

@interface HELPersonVC ()<HELPersonTableHeadViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,CWQButtonWithBadgeDelegate, UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,UIAlertViewDelegate>
@property (nonatomic,  strong) UICollectionView *collectionView;
@property (nonatomic,  strong) HELUserInfoM *userInfo;
@property (nonatomic,  strong) HELPersonTableHeadView *headView;

@property (nonatomic,  copy) NSDictionary *badgeDcit;
@property (nonatomic,  strong)UIButton *messageBtn;
@end
static NSString *cellID = @"HELPersonCollectionViewCellID";
static NSString *headerId = @"HELPersonTableHeadViewID";

@implementation HELPersonVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor  whiteColor];
   
    [self titleView:@"我的"];
    self.collectionView.backgroundColor = kAppBg;
    defineWeakSelf;
    [self.collectionView wsj_HeaderRefreshBlock:^{
        [weakSelf cwqGetWebData];
    }];

    [self rightBtn];
}
- (void)viewWillAppear:(BOOL)animated {
     self.automaticallyAdjustsScrollViewInsets = NO;
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    [self cwqGetWebData];
}

- (void)viewWillDisappear:(BOOL)animated {
    //    NSLog(@"%@",[self.navigationController viewControllers]);
//    if ([self.navigationController viewControllers].count > 1) {
    
        [self.navigationController setNavigationBarHidden:NO animated:YES];
//    }
}


- (void)rightBtn {
    
    //消息
    
    UIButton *messageBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 44, 20, 44, 44)];
    [messageBtn addTarget:self action:@selector(cwq_clickButton:) forControlEvents:UIControlEventTouchUpInside];
    [messageBtn setImage:[UIImage imageNamed:@"铃铛 "] forState:UIControlStateNormal];
    [self.view addSubview:messageBtn];
    _messageBtn = messageBtn;
}


- (void)cwq_clickButton:(UIButton *)btn {
    HELMeetingInfo *meetingInfoVC = [HELMeetingInfo new];
    meetingInfoVC.title = @"会议信息";
    [self.navigationController pushViewController:meetingInfoVC animated:YES];
}

- (void)setBadgeDcit:(NSDictionary *)badgeDcit {
    _badgeDcit = badgeDcit;
    if ([badgeDcit[@"noticeUnRead"] integerValue] > 0) {
        [self.messageBtn setImage:[UIImage imageNamed:@"消息提醒"] forState:UIControlStateNormal];
    }else {
        [self.messageBtn setImage:[UIImage imageNamed:@"铃铛 "] forState:UIControlStateNormal];
    }
    [self.collectionView reloadData];
    
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
       UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; // 自定义的布局对象
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 49) collectionViewLayout:layout];
        _collectionView.backgroundColor = kAppBg;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        // 注册cell、sectionHeader、sectionFooter
        [_collectionView registerNib:[UINib nibWithNibName:@"HELPersonCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:cellID];
        [_collectionView registerNib:[UINib nibWithNibName:@"HELPersonTableHeadView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId];

        [self.view addSubview:_collectionView];
    }
    return _collectionView;
    
}

- (void)cwqGetWebData {

    helUserInfo
    defineWeakSelf;
    /*
     *获取角标
     */
     NSDictionary *param = @{@"userId":userInfo.userId};
    [[HELNetworkManager sharedMg] GET:helStatusBagueUrl parameters:param success:^(id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            cwqHudRequestError(responseObject[@"exception"]);
        }else {
            if ([responseObject count] > 0) {
                weakSelf.badgeDcit = responseObject[0];
            }
        }
        [weakSelf.collectionView.header endRefreshing];
    } failure:^(NSString *err) {
        cwqHudRequestError(err);
        [weakSelf.collectionView.header endRefreshing];
    }];

}


#pragma mark UICollectionViewDataSource

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat w = kScreenWidth;
    CGFloat h =44;
    return CGSizeMake(w, h);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 5, 5, 5);
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 5.f;
}



- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
//    CGFloat height = 0.493*kScreenHeight;
    return (CGSize){kScreenWidth,headViewHeight};
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 5;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    HELPersonCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    cell.badge.hidden = YES;
    switch (indexPath.row) {
        case 0:{
            [cell.leftIcon setImage:[UIImage imageNamed:@"个人收藏"]];
            cell.title.text = @"收藏";
        }
            break;
        case 1:{
            [cell.leftIcon setImage:[UIImage imageNamed:@"错题"]];
            cell.title.text = @"错题集";
        }
            break;
         
        case 2:{
            [cell.leftIcon setImage:[UIImage imageNamed:@"下载"]];
            cell.title.text = @"下载";
        }
            break;
        case 3:{
            [cell.leftIcon setImage:[UIImage imageNamed:@"修改密码"]];
            cell.title.text = @"修改密码";
        }
            break;
            
        case 4:{
            [cell.leftIcon setImage:[UIImage imageNamed:@"设置"]];
            cell.title.text = @"设置";
        }
            break;
            
            
        default:
            break;
    }

    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    switch (indexPath.row) {
        case 0:{
            HELCompulsoryVC *electVC = [[HELCompulsoryVC alloc] initWithType:HELcourseTypeCollectStatus];
            electVC.title = @"收藏";
            [self.navigationController pushViewController:electVC animated:YES];
        }
            break;
        case 1:{
            HELStatisticVC *statisticVC = [HELStatisticVC new];
            statisticVC.title = @"错题集";
            [self.navigationController pushViewController:statisticVC animated:YES];
        }
            break;
        case 2:{
            HELDownloadVC *downloadVC = [HELDownloadVC new];
            downloadVC.title = @"我的下载";
            [self.navigationController pushViewController:downloadVC animated:YES];
        }
            break;
  
        case 3:{
            HELModifyPwdVC *modifyPwdVC = [HELModifyPwdVC new];
            modifyPwdVC.title = @"修改密码";
            [self.navigationController pushViewController:modifyPwdVC animated:YES];
        }
            break;
            
        case 4:{
            HELPersonSettingVC *settingVC = [[HELPersonSettingVC alloc] init];
            settingVC.userInfoModel = self.userInfo;
            [self.navigationController pushViewController:settingVC animated:YES];
        }
            break;
            
        default:
            break;
    }
    
}



- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
 if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        HELPersonTableHeadView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerId forIndexPath:indexPath];
     [headerView sendSubviewToBack:headerView.backgroundImageView];
     headerView.compursol.layer.cornerRadius = 10;
     headerView.compursol.layer.masksToBounds = YES;
     headerView.exam.layer.cornerRadius = 10;
     headerView.exam.layer.masksToBounds = YES;
     headerView.headBtn.layer.cornerRadius = 30;
     headerView.headBtn.layer.borderWidth = 1.0;
     headerView.headBtn.layer.borderColor = [UIColor whiteColor].CGColor;
     headerView.headBtn.layer.masksToBounds = YES;
     
     
     HELUserInfoM *userInfo = [HELAppManager userInfo];
     [headerView.headBtn sd_setImageWithURL:[NSURL URLWithString:userInfo.photoShowMap.mini] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"headPhoto"]];
     headerView.name.text = userInfo.trueName;
     [headerView setBadge:self.badgeDcit];
     headerView.delegate = self;
     _headView = headerView;
        return headerView;
    }
     return nil;
}


#pragma mark-------------HELPersonTableHeadViewDelegate ----------------

- (void)headBtnClick {
    
    UIActionSheet *actionSheetView = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册" ,nil];
    [actionSheetView showInView:self.navigationController.view];
}

- (void)headviewDidSelect:(NSInteger)index {

    switch (index) {
        case 1:{
            HELCompulsoryVC *compulsoryVC = [[HELCompulsoryVC alloc] initWithType:HELcourseTypeRequiredStatus];
            compulsoryVC.title = @"必修";
//            compulsoryVC
            [self.navigationController pushViewController:compulsoryVC animated:YES];
        }
            break;
        case 2:{

            HELExamVC *examVC = [HELExamVC new];
            //            examVC.title = @"我的考试";
            [self.navigationController pushViewController:examVC animated:YES];
        }
            
            break;
        case 3:{
            HELSigninVC *signinVC = [HELSigninVC new];
            signinVC.title = @"签到课程";
            [self.navigationController pushViewController:signinVC animated:YES];
         
        }
            
            break;
            
        default:
            break;
    }

}


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 0) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera ]) {
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        }
        
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        
        [self presentViewController:imagePicker animated:YES completion:nil];
    }else if(buttonIndex == 1){
        
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        [self presentViewController:imagePicker animated:YES completion:nil];
        
    }
    
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = info[UIImagePickerControllerEditedImage];
//    [self.headView.headBtn setImage:img forState:UIControlStateNormal];
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self uploadHeadPhoto:img];
}

/*
 *上传头像
 */
- (void)uploadHeadPhoto:(UIImage *)image{
    
    helUserInfo
    weakSelf_define;
    cwqHud(self.view);
    NSDictionary *param = @{@"userId":userInfo.userId};
    
    [[HELNetworkManager sharedMg] UPLOAD:helUploadHeadPhotofoUrl parameters:param image:image progress:^(CGFloat percent) {
        
    } success:^(id responseObject) {
        if (responseObject[@"exception"]) {
            cwqHudRequestError(responseObject[@"exception"]);
        }else {
            HELUserInfoM *userInfo = [HELAppManager userInfo];
            userInfo.photo = responseObject[@"root"];
            [weakSelf uploadImageName:@{@"photo":responseObject[@"root"]}];
        }
    } failure:^(NSString *err) {
        cwqHudRequestError(err);
    }];
    
}

/*
 *修改个人信息
 */

- (void)uploadImageName:(NSDictionary *)dict {
    NSMutableDictionary *muDict = [dict mutableCopy];
    __block HELUserInfoM *userInfo = [HELAppManager userInfo];
    userInfo.photo = dict[@"photo"];
    if (!userInfo.userId) {
        alertMessage(@"用户id获取失败");
        return;
    }
    weakSelf_define;
    cwqHud(self.view);
    [muDict setObject:userInfo.userId forKey:@"userId"];
    [[HELNetworkManager sharedMg] GET:helUpdateUserInfoUrl parameters:muDict success:^(id responseObject) {
        
        if (responseObject[@"exception"]) {
            cwqHudRequestError(responseObject[@"exception"]);
        }else {
            cwqHudSuccess(hud)
            [weakSelf updateLocalUserInfo:userInfo];
            [weakSelf.collectionView reloadData];
        }
        
        
    } failure:^(NSString *err) {
        cwqHudRequestError(err);
        
    }];
    
}



- (void)updateLocalUserInfo:(HELUserInfoM *)newInfo {

    newInfo.photo = newInfo.photo;
        NSString *baseURL = [[[HELNetworkManager sharedMg] getBaseUrl] stringByAppendingString:@"/upload/userphoto/"];
    if (!newInfo.photoShowMap) {
        newInfo.photoShowMap = [HELPicModel new];
    }
    newInfo.photoShowMap.mini = [baseURL stringByAppendingString:newInfo.photo];
    [HELAppManager saveUseInfo:[newInfo mj_keyValues]];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
